<template>
  <div class="changeView">
    <div class="viewBox">
      <div class="text-13px my-10px text-center">选择展示组件</div>
      <el-checkbox-group v-model="sorts">
        <el-checkbox
          :label="change.value"
          v-for="(change, index) in changes"
          :key="index"
          :disabled="change.disabled"
          >{{ change.key }}</el-checkbox
        >
      </el-checkbox-group>
    </div>
    <div class="viewBox">
      <div class="text-13px my-10px text-center">拖拽标签改变顺序</div>
      <div
        class="sortItem"
        v-for="(item, index) in recordData"
        :key="index + item.value"
        draggable="true"
        @dragstart="dragstart($event, index)"
        @dragenter="dragenter($event, index)"
        @dragend="dragend($event)"
      >
        {{ item.key }}
      </div>
    </div>
  </div>
</template>

<script setup name="content">
import { getCurrentInstance } from 'vue'

const { proxy } = getCurrentInstance()
const props = defineProps({
  sortArray: {
    type: Array,
    required: true
  },
  changeContent: {
    type: Array,
    required: true
  },
  tagType: {
    type: String,
    required: true
  }
})

const changes = ref([])
const sorts = ref([])
const recordData = ref([])

// 监听传入组件数组
watch(
  () => props.changeContent,
  val => {
    sorts.value = [...props.sortArray.map(v => v.value)]
    changes.value = [...props.changeContent]
    recordData.value = [...props.sortArray]
  },
  { immediate: true, deep: true }
)

// 监听选择组件变化
watch(sorts, val => {
  if (val) {
    recordData.value = changes.value.filter(v => {
      const name = v.value
      if (val.indexOf(name) > -1) {
        return v
      }
    })
  }
})

// 拖拽事件
const dragIndex = ref(0)
function dragstart(e, index) {
  dragIndex.value = index
  console.log(e.pageX, e.pageY)
}

const targetIndex = ref(0)
function dragenter(e, index) {
  if (index !== dragIndex.value) {
    targetIndex.value = index
  }
}

function dragend() {
  const newArray = [...recordData.value]
  const dragItem = newArray[dragIndex.value]
  const item = newArray[targetIndex.value]
  newArray.splice(dragIndex.value, 1, item)
  newArray.splice(targetIndex.value, 1, dragItem)
  recordData.value = newArray
}
function exposeSort() {
  const array = recordData.value.map(v => {
    if (sorts.value.indexOf(v.value) > -1) {
      return v
    }
  })
  return array
}
defineExpose({ exposeSort })
</script>

<style scoped lang="scss">
.changeView {
  display: flex;
  justify-content: space-around;
  margin-bottom: 10px;
  .viewBox {
    width: 48%;
    background-color: #f8f5f5;
    padding: 10px;
    height: 400px;
    overflow-y: auto;
    border-radius: 5px;
    position: relative;
  }
  .sortItem {
    @apply w-full text-center mt-10px;
    line-height: 40px;
    border: 1px solid #bdb3b3;
    border-radius: 5px;
    cursor: pointer;
  }
}
</style>
